package be.pluyckx.batteryprogress.utils.calculator;

/**
 * Created by Philip Luyckx on 8/08/13.
 */
public class RealTimeProgressCalculator extends ProgressCalculator {

  public RealTimeProgressCalculator() {
  }

  @Override
  public Result calculate(DataCollection data, Parameters params) {
    if (params.mOrdered == Parameters.ORDERED_OLD_LOWEST_INDEX) {
      return calculate(data, params, data.size() - 1);
    } else {
      return calculate(data, params, 0);
    }
  }

  @Override
  public Result calculate(DataCollection data, Parameters params, int index) {
    if (data.size() < 2 || index < 0) {
      return null;
    }

    DataItem oldest;
    DataItem newest;

    if (params.mOrdered == Parameters.ORDERED_OLD_LOWEST_INDEX) {
      if (index - 1 < 0) {
        return null;
      }

      newest = data.get(index);
      oldest = data.get(index - 1);
    } else {
      if (index + 1 >= data.size()) {
        return null;
      }

      newest = data.get(index);
      oldest = data.get(index + 1);
    }

    if (newest.getState() != oldest.getState()) {
      oldest = newest;
    }

    return average(oldest, newest);
  }
}
